<template>
  <div class="edit-container">
    <el-form ref="ruleFormRef" :model="form" label-width="120px" size="large" class="form-container" :rules="rules">
    <el-row></el-row><el-col :span="12"></el-col>
      <el-row>
        <el-col :span="12">
      <el-form-item label="客户姓名" prop="customerName" required>
        <el-input v-model="form.customerName" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="身份证号" prop="idcard" required>
        <el-input v-model="form.idcard" />
      </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="出生日期">
        <div class="block">
          <el-date-picker v-model="form.birthday" type="date" placeholder="请选择出生日期" :size="size"
                          style="width: 200px" />
        </div>
      </el-form-item>
        </el-col>
          <el-col :span="12">
      <el-form-item label="年龄">
        <el-input v-model="form.customerAge" disabled />
      </el-form-item>
          </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="性别" prop="customerSex" required>
        <el-select v-model="form.customerSex" clearable placeholder="请选择性别" style="width: 200px">
          <el-option v-for="item in optionSex" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="血型">
        <el-select v-model="form.bloodType" clearable placeholder="请选择血型" style="width: 200px">
          <el-option v-for="item in optionBloodType" :key="item.value" :label="item.label"
                     :value="item.value" />
        </el-select>
      </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="身高">
        <el-input v-model="form.height" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="体重">
        <el-input v-model="form.weight" />
      </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="身体状况">
        <el-input v-model="form.psychosomaticState" type="textarea" :rows="2" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="家属姓名">
        <el-input v-model="form.familyMember" />
      </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="联系电话">
        <el-input v-model="form.contactTel" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="楼号" prop="buildingNo" required>
        <el-select v-model="form.buildingNo" clearable placeholder="请选择楼号" style="width: 200px">
          <el-option v-for="item in optionBuildinngNo" :key="item.value" :label="item.label"
                     :value="item.value" />
        </el-select>
      </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="房间号" prop="roomNo" required>
        <el-input v-model="form.roomNo" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="床位号" prop="bedId" required>
        <el-select v-model="form.bedId" clearable placeholder="请选择床位号" style="width: 200px">
          <el-option v-for="item in optionBedId" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
      <el-form-item label="入住时间" prop="checkinDate" required>
        <div class="block">
          <el-date-picker v-model="form.checkinDate" type="date" placeholder="请选择入住日期" :size="size"
                          style="width: 200px" />
        </div>
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="合同到期时间" prop="expirationDate" required>
        <div class="block">
          <el-date-picker v-model="form.expirationDate" type="date" placeholder="请选择合同到期日期" :size="size"
                          style="width: 200px" />
        </div>
      </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="身份证照片">
        <div class="idcard-photos-container">
          <div class="photo-item">
            <el-upload :action="uploadUrl" :show-file-list="false" list-type="picture-card"
                       :on-success="handleFrontSuccess" :before-upload="beforeUpload" accept="image/*"
                       :headers="uploadHeaders">
              <!-- 上传Ret -->
              <img v-if="form.idcardFront" :src="getImageUrl(form.idcardFront)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <div class="photo-label">身份证正面</div>
          </div>

          <div class="photo-item">
            <el-upload :action="uploadUrl" :show-file-list="false" list-type="picture-card"
                       :on-success="handleBackSuccess" :before-upload="beforeUpload" accept="image/*"
                       :headers="uploadHeaders">
              <!-- 上传Ret -->
              <img v-if="form.idcardBack" :src="getImageUrl(form.idcardBack)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
            <div class="photo-label">身份证反面</div>
          </div>
        </div>
      </el-form-item>

      <el-form-item class="form-actions">
        <div class="action-buttons">
          <el-button type="primary" @click="onSubmit" size="large">保存</el-button>
          <el-button @click="cancleEdit" size="large">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name='edit'>
import { ref, reactive, watch } from "vue";
import { saveOrUpdateInfo, getById } from "@/api/customer/checkIn/index.js";
import { ElMessageBox, ElNotification } from 'element-plus'
import { useUserStore } from "@/stores/userStore.js";
import { onMounted } from "vue";

const userStore = useUserStore();
const uploadHeaders = {
  Authorization: userStore.getToken,
}

// 表单信息
const form = ref({
  customerName: '',
  customerAge: '',
  customerSex: '',
  birthday: '',
  idcard: '',
  bloodType: '',
  height: '',
  weight: '',
  familyMember: '',
  buildingNo: '',
  roomNo: '',
  bedId: '',
  contactTel: '',
  checkinDate: '',
  expirationDate: '',
  psychosomaticState: '',
  idcardFront: '',
  idcardBack: '',
})

// 代表父组件传过来的closeEdit函数
const { closeEdit, editId } = defineProps(['closeEdit', 'editId'])

// 创建引用 用于表单必选项验证
const ruleFormRef = ref();

// 保存按钮点击事件
const onSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      saveOrUpdateInfo(form.value).then(success => {
        ElNotification({
          title: '消息',
          type: 'success',
          message: "保存成功",
        })
        closeEdit(true);
      })
    } else {
      ElNotification({
        title: '错误',
        type: 'error',
        message: "请填写所有必选项",
      })
      return false;
    }
  })
}

// 点击取消按钮
const cancleEdit = () => {
  closeEdit(false);
}

// 当修改操作的到时候 根据主键查询
const pageGetById = async () => {
  try {
    const user = await getById(editId);
    if (user) {
      form.value = user;
      // 如果已有身份证号但无性别数据，尝试从身份证号提取
      if (user.idcard && !user.customerSex && user.idcard.length === 18) {
        form.value.customerSex = extractSexFromIdCard(user.idcard);
      }
    } else {
      console.warn("未找到id");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
}

// 获取API基础URL
const api_url = import.meta.env.VITE_API_SERVER
const uploadUrl = `${api_url}/upload`

// 获取图片完整URL
const getImageUrl = (fileId) => {
  return `${api_url}/downlod/${fileId}`;
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElNotification.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElNotification.error('图片大小不能超过5MB!');
    return false;
  }
  return true;
}

// 正面图片上传成功
const handleFrontSuccess = (response) => {
  // console.log(response);
  // const { id } = response;
  const { code, data, msg } = response;
  if (code == 200) {
    if (data.id) {
      form.value.idcardFront = data.id;

      ElNotification.success('身份证正面图片上传成功');
    } else {
      ElNotification.error('身份证正面图片上传失败');
    }
  }
}
// 背面图片上传成功
const handleBackSuccess = (response) => {

  const { code, data, msg } = response;
  if (code == 200) {
    if (data.id) {
      form.value.idcardBack = data.id;

      ElNotification.success('身份证背面图片上传成功');
    } else {
      ElNotification.error('身份证背面图片上传失败');
    }
  }
}

onMounted(() => {
  if (editId) {
    pageGetById()
  }
})

// ***** 自动填充功能 *****
// 从身份证号提取出生日期
const extractBirthdayFromIdCard = (idcard) => {
  if (!idcard || idcard.length < 18) {
    return null;
  }

  const birthStr = idcard.substring(6, 14);
  const year = birthStr.substring(0, 4);
  const month = birthStr.substring(4, 6);
  const day = birthStr.substring(6, 8);

  return `${year}-${month}-${day}`;
};

// 从出生日期计算年龄
const extractAgeFromBirthday = (birthday) => {
  if (!birthday) {
    return '';
  }

  const birthDate = new Date(birthday);
  const today = new Date();

  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age.toString();
};

// 从身份证号提取性别（第17位，奇数为男，偶数为女）
const extractSexFromIdCard = (idcard) => {
  if (!idcard || idcard.length < 18) {
    return '';
  }

  const sexNum = parseInt(idcard.charAt(16));
  return sexNum % 2 === 1 ? '0' : '1';
};

// 监听身份证号变化
watch(() => form.value.idcard, (newIdcard) => {
  if (newIdcard && newIdcard.length === 18) {
    // 提取并设置出生日期
    const birthday = extractBirthdayFromIdCard(newIdcard);
    if (birthday) {
      form.value.birthday = birthday;
      form.value.customerAge = extractAgeFromBirthday(birthday);
    }

    // 提取并设置性别
    form.value.customerSex = extractSexFromIdCard(newIdcard);
  }
});

// 监听生日变化
watch(() => form.value.birthday, (newBirthday) => {
  form.value.customerAge = extractAgeFromBirthday(newBirthday);
});

// 表单验证规则 必选项
const rules = {
  customerName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  customerSex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  idcard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && value.length !== 18) {
          callback(new Error('身份证号必须是18位'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  buildingNo: [{ required: true, message: '请选择楼号', trigger: 'blur' }],
  roomNo: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  bedId: [{ required: true, message: '请选择床位号', trigger: 'blur' }],
  checkinDate: [{ required: true, message: '请选择入住日期', trigger: 'change' }],
  expirationDate: [{ required: true, message: '请选择合同到期日期', trigger: 'change' }],
  idcardFront: [{ required: true, message: '请上传身份证正面照片', trigger: 'change' }],
  idcardBack: [{ required: true, message: '请上传身份证背面照片', trigger: 'change' }]
}

// 性别选择器
const optionSex = [
  { value: '0', label: '男' }, { value: '1', label: '女' }
]

// 血型选择器
const optionBloodType = [
  { value: 'A', label: 'A' }, { value: 'B', label: 'B' },
  { value: 'O', label: 'O' }, { value: 'AB', label: 'AB' },
]

// 楼号选择器
const optionBuildinngNo = [
  { value: '1', label: '1号楼' }, { value: '2', label: '2号楼' }
]

// 床位号选择器
const optionBedId = [
  { value: '1', label: '1号床' }, { value: '2', label: '2号床' }
]
</script>

<style scoped>
/* 编辑表单外层容器样式 */
.edit-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100%;
  box-sizing: border-box;
}

/* 表单内容区域样式 */
.form-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表单项通用样式 */
.el-form-item {
  margin-bottom: 22px;
}

/* 身份证照片区域容器 */
.idcard-photos-container {
  display: flex;
  gap: 30px;
  margin-top: 10px;
}

/* 单个照片项样式 */
.photo-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar {
  width: 148px;
  height: 148px;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.photo-label {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

/* 表单操作按钮区域样式 */
.form-actions {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

/* 操作按钮容器样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 响应式设计 - 屏幕宽度小于768px时的样式 */
@media (max-width: 768px) {
  .form-container {
    padding: 16px;
  }

  .el-form-item {
    margin-bottom: 18px;
  }

  .idcard-photos-container {
    flex-direction: column;
    gap: 20px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }

  .el-button {
    width: 100%;
  }
}
</style>